package com.police.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.police.R;
import com.police.adapter.BenJiUserListAdapter;
import com.police.adapter.EventLayoutThreeAdapter;
import com.police.adapter.SearchRecordListAdapter;
import com.police.adapter.ShiJianItemOneAdapter;
import com.police.adapter.ShiJianListViewAdapter;
import com.police.controller.AsyncHandler;
import com.police.controller.Controller;
import com.police.controller.DefaultController;
import com.police.controller.DefaultRequest;
import com.police.controller.IResponse;
import com.police.controller.JSONResp;
import com.police.db.DBHelper;
import com.police.db.EventManager;
import com.police.db.SearchRecord;
import com.police.db.SearchRecordManager;
import com.police.db.User;
import com.police.db.UserManager;
import com.police.model.SearchRecordDetailsBean;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基类
 *
 * @author chenyang2
 */
public class BaseActivity extends Activity {

    public SharedPreferences preference;
    private PopupWindow popupWindow, popuWindowEventOneItem,
            popuWindowEventThreeItem, setPopuWindow, searchPop;// popu窗口
    private PopupWindow addEventPopu;// 增加事件窗口

    private LayoutInflater inflater;
    private View viewLayout;// popuwindow窗口布局
    private LinearLayout viewLayoutTwo;
    private LinearLayout viewLayoutThree;
    private LinearLayout addEventLayout;
    private LinearLayout viewLayoutSet;
    private LinearLayout searchRecordLayout;
    private ListView shiJianListView, event_listView, listViewThree;// 事件列表（管理员）

    private com.police.db.Event eventBean;// 事件详情
    
    private String newVersionUrl;


    /**
     * 删除用户相关
     */
    private DeleteUserListAdapter deleteUserListAdapter;
    private List<String> usersList = new ArrayList<String>();

    private List<ShiJianItemThreeBean> itemOneBeanListThree = new ArrayList<ShiJianItemThreeBean>();
    private List<SearchRecordDetailsBean> searchDetailsBean = new ArrayList<SearchRecordDetailsBean>();
    private Button shiJianBtn, setBtn;
    public ProgressDialog progressDialog;
    private RelativeLayout progressBarLayout;
    private TextView addEvent;
    private TextView sureTextView, giveUpTextView;
    public DBHelper helper = new DBHelper(BaseActivity.this);

    // 事件列表
    public List<com.police.db.Event> itemOneBeanList = new ArrayList<com.police.db.Event>();
    // 办事人员（即 被本机管理员所管理的本机所有用户）
    public List<User> shiJianBeanList = new ArrayList<User>();

    // 搜索记录列表
    public List<SearchRecord> searchRecordList = new ArrayList<SearchRecord>();
    /**
     * 设置相关
     */

    private TextView addUserText;
    private TextView deleteUserText;
    private TextView presentLoginUserText;
    private TextView exitText;
    private ListView benjiUserListView;

    /**
     * 增加用户窗口相关
     */
    private PopupWindow addUserPopu;
    private RelativeLayout addUserLayout;
    private Button addUserBtnSure;// 确定按钮
    private EditText userNameEdit;

    /**
     * 删除用户窗口
     */
    private PopupWindow deleteUserPopu;
    private RelativeLayout deleteUserLayout;

    /**
     * 搜索记录 人员列表窗口
     */
    private PopupWindow searchUsersPopu;
    private LinearLayout searchUsersLayout;
    private Button searchRecord;
    /**
     * 添加事件相关
     */
    private EditText eventEdit, nianEdit, yueEdit, dayEdit, aboutPersonEdit,
            phoneNumEdit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preference = this.getSharedPreferences("KeySet", 0);
        if (preference.getInt("banJin", 700) == 700) {
            SharedPreferences.Editor editor = preference.edit();
            editor.putInt("banJin", 700).commit();
        }
        if (preference.getBoolean("isOpenBaoJing", true)) {
            SharedPreferences.Editor editor = preference.edit();
            editor.putBoolean("isOpenBaoJing", true).commit();
        }
    }

    /**
     * 事件一级菜单显示
     */
    private void initPopupWindow(View view1, int height) {
        popupWindow = new PopupWindow(initPopuLayout(), 360, height);
        popupWindow.setAnimationStyle(R.style.menuPopupAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initPopuLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewLayout = (LinearLayout) inflater.inflate(
                R.layout.search_record_view, null);
        shiJianListView = (ListView) viewLayout.findViewById(R.id.record_list);
        ShiJianListViewAdapter shiJianListViewAdapter = new ShiJianListViewAdapter(
                this, shiJianBeanList);
        shiJianListView.setAdapter(shiJianListViewAdapter);
        shiJianListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        // 点击办事人员，进行查询该办事人员所办理的事件
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                        EventManager eventManager = new EventManager(helper);
                        // 查询出 点击某个办事人员所办的事件
                        itemOneBeanList = eventManager.query(shiJianBeanList
                                .get(arg2).name);
                        if (itemOneBeanList.size() == 0) {
                            Toast.makeText(BaseActivity.this, "该人员没有办事记录", 5000)
                                    .show();
                        } else {
                            showpopuWindowEventOneItem(shiJianBtn, 280, -280);
                        }

                    }
                });
        return viewLayout;
    }

    public void showPopupWindow(View v, int height, int fromX) {

        shiJianBtn = (Button) v;

        // if (popupWindow == null) {
        initPopupWindow(v, height);
        // }
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.update();
            popupWindow.showAtLocation(v, Gravity.BOTTOM, fromX, 68);
        }
    }

    /**
     * 事件二级菜单
     *
     * @param view1
     * @param height
     */
    private void initpopuWindowEventOneItem(View view1, int height) {
        popuWindowEventOneItem = new PopupWindow(
                initpopuWindowEventOneItemLayout(), 420, height);
        popuWindowEventOneItem.setAnimationStyle(R.style.PopuAnimation);
        popuWindowEventOneItem.setFocusable(true);
        popuWindowEventOneItem.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowEventOneItemLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewLayoutTwo = (LinearLayout) inflater.inflate(R.layout.event_view,
                null);
        event_listView = (ListView) viewLayoutTwo.findViewById(R.id.event_list);

        /**
         * 添加事件监听
         */
        addEvent = (TextView) viewLayoutTwo.findViewById(R.id.add);
        if (preference.getBoolean("isAdmin", false)) {
            addEvent.setVisibility(View.GONE);
        }
        addEvent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (popuWindowEventOneItem != null
                        && popuWindowEventOneItem.isShowing()) {
                    popuWindowEventOneItem.dismiss();
                }
                showpopuWindowAddEvent(shiJianBtn, 340, -300);
            }
        });

        ShiJianItemOneAdapter shiJianListViewAdapter = new ShiJianItemOneAdapter(
                this, itemOneBeanList);
        event_listView.setAdapter(shiJianListViewAdapter);
        event_listView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {

                        eventBean = itemOneBeanList.get(arg2);
                        if (popuWindowEventOneItem != null
                                && popuWindowEventOneItem.isShowing()) {
                            popuWindowEventOneItem.dismiss();
                        }
                        showpopuWindowEventThreeItem(shiJianBtn, 130, -280,
                                arg2);
                        // Toast.makeText(BaseActivity.this,
                        // "由于感觉需求稍微有点问题，没来得及沟通，这个窗口需要沟通后再弄....", 20000).show();
                    }
                });
        return viewLayoutTwo;
    }

    public void showpopuWindowEventOneItem(View v, int height, int fromX) {

        shiJianBtn = (Button) v;
        // if (popuWindowEventOneItem == null) {
        initpopuWindowEventOneItem(v, height);
        // }
        if (popuWindowEventOneItem.isShowing()) {
            popuWindowEventOneItem.dismiss();
        } else {
            popuWindowEventOneItem.update();
            popuWindowEventOneItem.showAtLocation(v, Gravity.BOTTOM, fromX, 68);
        }
    }

    /**
     * 增加事件菜单
     */
    private void initpopuWindowAddEvent(View view1, int height) {
        addEventPopu = new PopupWindow(initpopuWindowAddEventLayout(), 512,
                height);
        addEventPopu.setAnimationStyle(R.style.menuPopupAnimation);
        addEventPopu.setFocusable(true);
        addEventPopu.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowAddEventLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        addEventLayout = (LinearLayout) inflater.inflate(
                R.layout.add_event_view, null);
        sureTextView = (TextView) addEventLayout
                .findViewById(R.id.sureTextView);
        eventEdit = (EditText) addEventLayout.findViewById(R.id.event);
        nianEdit = (EditText) addEventLayout.findViewById(R.id.nian);
        yueEdit = (EditText) addEventLayout.findViewById(R.id.yue);
        dayEdit = (EditText) addEventLayout.findViewById(R.id.day);
        aboutPersonEdit = (EditText) addEventLayout
                .findViewById(R.id.aboutPerson);
        phoneNumEdit = (EditText) addEventLayout.findViewById(R.id.phoneNum);
        sureTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (eventEdit.getText().toString().equals("")) {
                    startAnimation(eventEdit);
                } else if (nianEdit.getText().toString().equals("")) {
                    startAnimation(nianEdit);
                } else if (yueEdit.getText().toString().equals("")) {
                    startAnimation(yueEdit);
                } else if (dayEdit.getText().toString().equals("")) {
                    startAnimation(dayEdit);
                } else if (aboutPersonEdit.getText().toString().equals("")) {
                    startAnimation(aboutPersonEdit);
                } else if (phoneNumEdit.getText().toString().equals("")) {
                    startAnimation(phoneNumEdit);
                }

                /**
                 * 将添加的内容保存到数据库
                 */
                else {
                    // DBHelper helper = new DBHelper(BaseActivity.this);
                    EventManager eventManager = new EventManager(helper);
                    String timeStr = nianEdit.getText().toString() + "-"
                            + yueEdit.getText().toString() + "-"
                            + dayEdit.getText().toString();
                    com.police.db.Event event = new com.police.db.Event(
                            preference.getString("loginUserName", ""),
                            eventEdit.getText().toString(), timeStr,
                            aboutPersonEdit.getText().toString(), phoneNumEdit
                            .getText().toString());
                    List<com.police.db.Event> events = new ArrayList<com.police.db.Event>();
                    events.add(event);
                    eventManager.add(events);
                    if (addEventPopu != null && addEventPopu.isShowing()) {
                        addEventPopu.dismiss();
                    }
                }
                //
            }
        });
        TextView add = (TextView) addEventLayout.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (addEventPopu != null && addEventPopu.isShowing()) {
                    addEventPopu.dismiss();
                }
            }
        });
        giveUpTextView = (TextView) addEventLayout
                .findViewById(R.id.giveUpTextView);
        giveUpTextView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (addEventPopu != null && addEventPopu.isShowing()) {
                    addEventPopu.dismiss();
                }
            }
        });
        return addEventLayout;
    }

    public void showpopuWindowAddEvent(View v, int height, int fromX) {

        if (addEventPopu == null) {
            initpopuWindowAddEvent(v, height);
        }
        if (addEventPopu.isShowing()) {
            addEventPopu.dismiss();
        } else {
            addEventPopu.update();
            addEventPopu.showAtLocation(v, Gravity.BOTTOM, fromX, 68);
        }
    }

    /**
     * 事件三级菜单
     */
    private void initpopuWindowEventThreeItem(View view1, int height,
                                              int positon) {
        popuWindowEventThreeItem = new PopupWindow(
                initpopuWindowEventThreeItemLayout(positon), 550, height);
        popuWindowEventThreeItem.setAnimationStyle(R.style.menuPopupAnimation);
        popuWindowEventThreeItem.setFocusable(true);
        popuWindowEventThreeItem.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowEventThreeItemLayout(final int position) {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewLayoutThree = (LinearLayout) inflater.inflate(
                R.layout.event_view_three, null);
        listViewThree = (ListView) viewLayoutThree.findViewById(R.id.listView);
        EventLayoutThreeAdapter shiJianListViewAdapter = new EventLayoutThreeAdapter(
                this, eventBean);
        listViewThree.setAdapter(shiJianListViewAdapter);
        listViewThree
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        // TODO Auto-generated method stub
                    }
                });

        Button deleteEventBtn = (Button) viewLayoutThree
                .findViewById(R.id.deleteEventBtn);
        TextView eventName = (TextView) viewLayoutThree
                .findViewById(R.id.eventName);
        eventName.setText(eventBean.name);
        deleteEventBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 删除该事件/
                EventManager eventManager = new EventManager(helper);
                eventManager.del(eventBean.name);
                Toast.makeText(BaseActivity.this, "成功删除事件" + eventBean.name,
                        5000).show();
                if (popuWindowEventThreeItem != null
                        && popuWindowEventThreeItem.isShowing()) {
                    popuWindowEventThreeItem.dismiss();
                }

            }
        });

        return viewLayoutThree;
    }

    public void showpopuWindowEventThreeItem(View v, int height, int fromX,
                                             int postion) {

        // if (popuWindowEventThreeItem == null) {
        initpopuWindowEventThreeItem(v, height, postion);
        // }
        if (popuWindowEventThreeItem.isShowing()) {
            popuWindowEventThreeItem.dismiss();
        } else {
            popuWindowEventThreeItem.update();
            popuWindowEventThreeItem.showAtLocation(v, Gravity.BOTTOM, fromX,
                    68);
        }
    }

    /**
     * 搜索记录列表
     */
    private void initSearchPopupWindow(View view1, int height) {
        searchPop = new PopupWindow(initSearchRecordPopuLayout(), 550, height);
        searchPop.setAnimationStyle(R.style.PopuAnimation);
        searchPop.setFocusable(true);
        searchPop.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initSearchRecordPopuLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        searchRecordLayout = (LinearLayout) inflater.inflate(
                R.layout.search_record_detail_view, null);
        ListView record_details_list = (ListView) searchRecordLayout
                .findViewById(R.id.record_details_list);
        SearchRecordListAdapter searchRecordListAdapter = new SearchRecordListAdapter(
                BaseActivity.this, searchRecordList);
        record_details_list.setAdapter(searchRecordListAdapter);
        return searchRecordLayout;
    }

    public void showSearchRecordPopu(View v, int height, int fromX) {
        initSearchPopupWindow(v, height);
        if (searchPop.isShowing()) {
            searchPop.dismiss();
        } else {
            searchPop.update();
            searchPop.showAtLocation(v, Gravity.BOTTOM, fromX, 68);
        }
    }

    /**
     * 设置窗口
     */

    private void initpopuWindowSetItem(View view1, int height) {
        if (preference.getBoolean("isAdmin", false)) {
            setPopuWindow = new PopupWindow(initpopuWindowSetItemLayout(), 620,
                    height);
        } else {
            setPopuWindow = new PopupWindow(initpopuWindowSetUserLayout(), 620,
                    height);
        }

        setPopuWindow.setAnimationStyle(R.style.menuPopupAnimation);
        setPopuWindow.setFocusable(true);
        setPopuWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowSetUserLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewLayoutSet = (LinearLayout) inflater.inflate(
                R.layout.setting_users_layout, null);
        presentLoginUserText = (TextView) viewLayoutSet
                .findViewById(R.id.presentUser);
        presentLoginUserText.setText("当前用户："
                + preference.getString("loginUserName", "当前没有用户登录"));
        exitText = (TextView) viewLayoutSet.findViewById(R.id.exit);
        exitText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(BaseActivity.this,
                        LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        
        
        TextView jianNewVersion = (TextView) viewLayoutSet.findViewById(R.id.jianNewVersion);
        jianNewVersion.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                requestNewVersion();
            }
        });

        addUserText = (TextView) viewLayoutSet.findViewById(R.id.addUserText);
        final EditText passWordEdit = (EditText) viewLayoutSet
                .findViewById(R.id.newPassWordEdit);
        final TextView sureText = (TextView) viewLayoutSet
                .findViewById(R.id.sureText);
        final TextView changePassword = (TextView) viewLayoutSet
                .findViewById(R.id.changePassword);
        changePassword.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (changePassword.getText().equals("[更改密码]")) {
                    passWordEdit.setVisibility(View.VISIBLE);
                    sureText.setVisibility(View.VISIBLE);
                    changePassword.setText("[取消]");
                } else {
                    passWordEdit.setVisibility(View.GONE);
                    sureText.setVisibility(View.GONE);
                    changePassword.setText("[更改密码]");
                }

            }
        });
        sureText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!passWordEdit.getText().toString().equals(" ")) {
                    UserManager userManager = new UserManager(helper);
                    userManager.changePassWord(
                            preference.getString("loginUserName", ""),
                            passWordEdit.getText().toString());
                    passWordEdit.setVisibility(View.GONE);
                    sureText.setVisibility(View.GONE);
                    changePassword.setText("[更改密码]");
                    Toast.makeText(BaseActivity.this, "更改密码成功", 5000).show();
                } else {
                    Toast.makeText(BaseActivity.this, "请输入新密码", 5000).show();
                }
            }
        });

        final EditText banJinEdit = (EditText) viewLayoutSet
                .findViewById(R.id.banJinEdit);
        final TextView banJinValue = (TextView) viewLayoutSet
                .findViewById(R.id.banJinValue);
        final TextView sureBtn = (TextView) viewLayoutSet
                .findViewById(R.id.sureBtn);
        final TextView closeText = (TextView) viewLayoutSet
                .findViewById(R.id.close);
        final TextView baoJingStatus = (TextView) viewLayoutSet
                .findViewById(R.id.baoJingStatus);
        if (preference.getBoolean("isOpenBaoJing", false)) {
            closeText.setText("关闭");
            baoJingStatus.setText("接近目标预警：" + "已开启");
        } else {
            closeText.setText("开启");
            baoJingStatus.setText("接近目标预警：" + "已关闭");
        }

        closeText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = preference.edit();
                if (closeText.getText().toString().equals("关闭")) {
                    editor.putBoolean("isOpenBaoJing", false).commit();
                    closeText.setText("开启");
                    baoJingStatus.setText("接近目标预警：" + "已关闭");
                } else if (closeText.getText().toString().equals("开启")) {
                    editor.putBoolean("isOpenBaoJing", true).commit();
                    closeText.setText("关闭");
                    baoJingStatus.setText("接近目标预警：" + "已开启");
                }
            }
        });

        banJinValue.setText("当前半径:"
                + String.valueOf(preference.getInt("banJin", 700)) + "米");
        /**
         * 编辑半径
         */
        final TextView banJiBtn = (TextView) viewLayoutSet
                .findViewById(R.id.banJiBtn);
        banJiBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (banJiBtn.getText().toString().equals("[编辑]")) {
                    banJinEdit.setVisibility(View.VISIBLE);
                    banJinValue.setVisibility(View.GONE);
                    sureBtn.setVisibility(View.VISIBLE);
                    banJiBtn.setText("[取消]");
                } else if (banJiBtn.getText().toString().equals("[取消]")) {
                    banJinEdit.setVisibility(View.GONE);
                    sureBtn.setVisibility(View.GONE);
                    banJinValue.setVisibility(View.VISIBLE);
                    banJiBtn.setText("[编辑]");
                }
            }
        });

        sureBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (banJinEdit.getText().toString().equals("")) {
                    startAnimation(banJinEdit);
                } else {
                    SharedPreferences.Editor editor = preference.edit();
                    editor.putInt("banJin",
                            Integer.parseInt(banJinEdit.getText().toString()))
                            .commit();
                    banJinEdit.setVisibility(View.GONE);
                    sureBtn.setVisibility(View.GONE);
                    banJinValue.setVisibility(View.VISIBLE);
                    banJiBtn.setVisibility(View.VISIBLE);
                    banJiBtn.setText("[编辑]");
                    banJinValue.setText("当前半径:"
                            + String.valueOf(preference.getInt("banJin", 0))
                            + "米");
                }
            }
        });

        return viewLayoutSet;
    }

    public View initpopuWindowSetItemLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewLayoutSet = (LinearLayout) inflater.inflate(R.layout.setting_view,
                null);
        presentLoginUserText = (TextView) viewLayoutSet
                .findViewById(R.id.presentUser);
        presentLoginUserText.setText("当前用户："
                + preference.getString("loginUserName", "当前没有用户登录"));
        exitText = (TextView) viewLayoutSet.findViewById(R.id.exit);
        exitText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(BaseActivity.this,
                        LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });

        benjiUserListView = (ListView) viewLayoutSet
                .findViewById(R.id.benjiUser);

        BenJiUserListAdapter benJiUserListAdapter = new BenJiUserListAdapter(
                BaseActivity.this, shiJianBeanList, preference, helper);
        benjiUserListView.setAdapter(benJiUserListAdapter);

        
        TextView checkNewVersion = (TextView)viewLayoutSet.findViewById(R.id.jianCeVersion);
        checkNewVersion.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				requestNewVersion();
			}
		});
        
        TextView close = (TextView) viewLayoutSet.findViewById(R.id.close);
        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
        addUserText = (TextView) viewLayoutSet.findViewById(R.id.addUserText);
        addUserText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 增加用户
                if (preference.getBoolean("isAdmin", false)) {
                    if (setPopuWindow != null && setPopuWindow.isShowing()) {
                        setPopuWindow.dismiss();
                    }
                    showpopuWindowAddUser(setBtn, 280, 160);
                } else {
                    Toast.makeText(BaseActivity.this, "您不是管理员，不能添加用户", 6000)
                            .show();
                }

            }
        });

        deleteUserText = (TextView) viewLayoutSet
                .findViewById(R.id.deleteUserText);
        deleteUserText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 删除用户
                /**
                 * 管理员登陆，首先显示办事人员列表
                 */
                if (setPopuWindow != null && setPopuWindow.isShowing()) {
                    setPopuWindow.dismiss();
                }
                UserManager userManager = new UserManager(helper);
                // 查询出办事人员
                shiJianBeanList = userManager.query();
                if (shiJianBeanList.size() == 0) {
                    Toast.makeText(BaseActivity.this, "当前没有用户", 5000).show();
                } else if (shiJianBeanList.size() == 1) {
                    showpopuWindowDeleteUser(setBtn, 280, 160);
                } else if (shiJianBeanList.size() == 2) {
                    showpopuWindowDeleteUser(setBtn, 310, 160);
                } else if (shiJianBeanList.size() == 3) {
                    showpopuWindowDeleteUser(setBtn, 340, 160);
                } else {
                    showpopuWindowDeleteUser(setBtn, 400, 160);
                }

            }
        });

        final EditText banJinEdit = (EditText) viewLayoutSet
                .findViewById(R.id.banJinEdit);
        final TextView banJinValue = (TextView) viewLayoutSet
                .findViewById(R.id.banJinValue);
        final TextView sureBtn = (TextView) viewLayoutSet
                .findViewById(R.id.sureBtn);
        final TextView closeText = (TextView) viewLayoutSet
                .findViewById(R.id.close);
        final TextView baoJingStatus = (TextView) viewLayoutSet
                .findViewById(R.id.baoJingStatus);
        if (preference.getBoolean("isOpenBaoJing", false)) {
            closeText.setText("关闭");
            baoJingStatus.setText("接近目标预警：" + "已开启");
        } else {
            closeText.setText("开启");
            baoJingStatus.setText("接近目标预警：" + "已关闭");
        }

        closeText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = preference.edit();
                if (closeText.getText().toString().equals("关闭")) {
                    editor.putBoolean("isOpenBaoJing", false).commit();
                    closeText.setText("开启");
                    baoJingStatus.setText("接近目标预警：" + "已关闭");
                } else if (closeText.getText().toString().equals("开启")) {
                    editor.putBoolean("isOpenBaoJing", true).commit();
                    closeText.setText("关闭");
                    baoJingStatus.setText("接近目标预警：" + "已开启");
                }
            }
        });

        banJinValue.setText("当前半径:"
                + String.valueOf(preference.getInt("banJin", 700)) + "米");
        /**
         * 编辑半径
         */
        final TextView banJiBtn = (TextView) viewLayoutSet
                .findViewById(R.id.banJiBtn);
        banJiBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (banJiBtn.getText().toString().equals("[编辑]")) {
                    banJinEdit.setVisibility(View.VISIBLE);
                    banJinValue.setVisibility(View.GONE);
                    sureBtn.setVisibility(View.VISIBLE);
                    banJiBtn.setText("[取消]");
                } else if (banJiBtn.getText().toString().equals("[取消]")) {
                    banJinEdit.setVisibility(View.GONE);
                    sureBtn.setVisibility(View.GONE);
                    banJinValue.setVisibility(View.VISIBLE);
                    banJiBtn.setText("[编辑]");
                }
            }
        });

        sureBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (banJinEdit.getText().toString().equals("")) {
                    startAnimation(banJinEdit);
                } else {
                    SharedPreferences.Editor editor = preference.edit();
                    editor.putInt("banJin",
                            Integer.parseInt(banJinEdit.getText().toString()))
                            .commit();
                    banJinEdit.setVisibility(View.GONE);
                    sureBtn.setVisibility(View.GONE);
                    banJinValue.setVisibility(View.VISIBLE);
                    banJiBtn.setVisibility(View.VISIBLE);
                    banJiBtn.setText("[编辑]");
                    banJinValue.setText("当前半径:"
                            + String.valueOf(preference.getInt("banJin", 0))
                            + "米");
                }
            }
        });

        return viewLayoutSet;
    }

    public void showpopuWindowSetItem(View v, int height, int fromX) {

        setBtn = (Button) v;
        // if (setPopuWindow == null) {
        initpopuWindowSetItem(v, height);
        // }
        if (setPopuWindow.isShowing()) {
            setPopuWindow.dismiss();
        } else {
            setPopuWindow.update();
            setPopuWindow.showAtLocation(v, Gravity.BOTTOM, fromX, 68);
        }
    }

    /**
     * 增加用户窗口
     */

    private void initpopuWindowAddUser(View view1, int height) {
        addUserPopu = new PopupWindow(initpopuWindowAddUserLayout(), 400,
                height);
        addUserPopu.setAnimationStyle(R.style.PopuAnimation);
        addUserPopu.setFocusable(true);
        addUserPopu.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowAddUserLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        addUserLayout = (RelativeLayout) inflater.inflate(
                R.layout.add_new_user_layout, null);
        addUserBtnSure = (Button) addUserLayout.findViewById(R.id.btnSure);
        userNameEdit = (EditText) addUserLayout.findViewById(R.id.userNameEdit);
        Button btnClose = (Button) addUserLayout.findViewById(R.id.btnClose);
        Button btnCancel = (Button) addUserLayout.findViewById(R.id.btnCancel);
        btnClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (addUserPopu != null && addUserPopu.isShowing()) {
                    addUserPopu.dismiss();
                }
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (addUserPopu != null && addUserPopu.isShowing()) {
                    addUserPopu.dismiss();
                }
            }
        });
        addUserBtnSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 添加用户到数据库
                // DBHelper helper = new DBHelper(BaseActivity.this);
                UserManager userManager = new UserManager(helper);
                if (!userNameEdit.getText().toString().equals("")) {
                    if (userManager.queryByLogin(userNameEdit.getText()
                            .toString())) {
                        Toast.makeText(BaseActivity.this, "该用户名已经存在", 5000)
                                .show();
                    } else {
                        User user = new User(userNameEdit.getText().toString(),
                                "000000", "", 0);
                        List<User> users = new ArrayList<User>();
                        users.add(user);
                        userManager.add(users);
                        Toast.makeText(BaseActivity.this,
                                "成功添加" + userNameEdit.getText().toString(),
                                5000).show();
                        if (addUserPopu != null && addUserPopu.isShowing()) {
                            addUserPopu.dismiss();
                        }
                    }
                } else {
                    Toast.makeText(BaseActivity.this, "名字不能为空", 5000).show();
                }

                // userManager.a
            }
        });
        return addUserLayout;
    }

    public void showpopuWindowAddUser(View v, int height, int fromX) {

        if (addUserPopu == null) {
            initpopuWindowAddUser(v, height);
        }
        if (addUserPopu.isShowing()) {
            addUserPopu.dismiss();
        } else {
            addUserPopu.update();
            addUserPopu.showAtLocation(v, Gravity.BOTTOM, fromX, 300);
        }
    }

    /**
     * 删除用户窗口
     */

    private void initpopuWindowDeleteUser(View view1, int height) {
        deleteUserPopu = new PopupWindow(initpopuWindowDeleteUserLayout(), 430,
                height);
        deleteUserPopu.setAnimationStyle(R.style.PopuAnimation);
        deleteUserPopu.setFocusable(true);
        deleteUserPopu.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowDeleteUserLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        deleteUserLayout = (RelativeLayout) inflater.inflate(
                R.layout.delete_user_layout, null);
        ListView userNameListView = (ListView) deleteUserLayout
                .findViewById(R.id.userNameListView);
        deleteUserListAdapter = new DeleteUserListAdapter();
        userNameListView.setAdapter(deleteUserListAdapter);
        Button btnSure = (Button) deleteUserLayout.findViewById(R.id.btnSure);
        Button btnCancel = (Button) deleteUserLayout
                .findViewById(R.id.btnCancel);
        Button btnClose = (Button) deleteUserLayout.findViewById(R.id.btnClose);
        btnSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (usersList.size() == 0) {
                    Toast.makeText(BaseActivity.this, "请选择要删除的用户", 5000).show();
                } else {
                    UserManager userManager = new UserManager(helper);
                    userManager.deleteUsers(usersList);
                    Toast.makeText(BaseActivity.this, "删除用户成功", 5000).show();
                    usersList.clear();
                }
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (deleteUserPopu != null && deleteUserPopu.isShowing()) {
                    deleteUserPopu.dismiss();
                }
            }
        });
        btnClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (deleteUserPopu != null && deleteUserPopu.isShowing()) {
                    deleteUserPopu.dismiss();
                }
            }
        });
        return deleteUserLayout;
    }

    public void showpopuWindowDeleteUser(View v, int height, int fromX) {

        // if (deleteUserPopu == null) {
        initpopuWindowDeleteUser(v, height);
        // }
        if (deleteUserPopu.isShowing()) {
            deleteUserPopu.dismiss();
        } else {
            deleteUserPopu.update();
            deleteUserPopu.showAtLocation(v, Gravity.BOTTOM, fromX, 300);
        }
    }

    /**
     * 搜索记录人员窗口（当登录者是管理员的时候，点击搜索记录按钮出现该窗口）
     */

    private void initpopuWindowSearchUsers(View view1, int height) {
        searchUsersPopu = new PopupWindow(initpopuWindowSearchUsersLayout(),
                400, height);
        searchUsersPopu.setAnimationStyle(R.style.menuPopupAnimation);
        searchUsersPopu.setFocusable(true);
        searchUsersPopu.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initpopuWindowSearchUsersLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        searchUsersLayout = (LinearLayout) inflater.inflate(
                R.layout.search_record_view, null);
        TextView searchUsersText = (TextView) searchUsersLayout
                .findViewById(R.id.searchUsersText);
        searchUsersText.setText("搜索记录人员");
        shiJianListView = (ListView) searchUsersLayout
                .findViewById(R.id.record_list);
        ShiJianListViewAdapter shiJianListViewAdapter = new ShiJianListViewAdapter(
                this, shiJianBeanList);
        shiJianListView.setAdapter(shiJianListViewAdapter);
        shiJianListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        // //点击办事人员，进行查询该办事人员所办理的事件
                        //
                        // EventManager eventManager = new EventManager(helper);
                        // //查询出 点击某个办事人员所办的事件
                        // itemOneBeanList =
                        // eventManager.query(shiJianBeanList.get(arg2).name);
                        // showpopuWindowEventOneItem(shiJianBtn, 280, 20);
                        SearchRecordManager searchRecordManager = new SearchRecordManager(
                                helper);
                        searchRecordList = searchRecordManager
                                .query(shiJianBeanList.get(arg2).name);
                        if (searchRecordList.size() == 0) {
                            Toast.makeText(BaseActivity.this, "该人员没有搜索记录", 6000)
                                    .show();
                        } else {
                            if (searchUsersPopu != null
                                    && searchUsersPopu.isShowing()) {
                                searchUsersPopu.dismiss();
                            }
                            showSearchRecordPopu(searchRecord, 300, 36);
                        }
                    }
                });

        return searchUsersLayout;
    }

    public void showpopuWindowSearchUsers(View v, int height, int fromX) {
        searchRecord = (Button) v;
        initpopuWindowSearchUsers(v, height);
        if (searchUsersPopu.isShowing()) {
            searchUsersPopu.dismiss();
        } else {
            searchUsersPopu.update();
            searchUsersPopu.showAtLocation(v, Gravity.BOTTOM, fromX, 68);
        }
    }

    /**
     * 事件列表（管理员查看的以及菜单）
     *
     * @author
     */
    public class ShiJianBean {
        private String name;
        private String eventNum;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getEventNum() {
            return eventNum;
        }

        public void setEventNum(String eventNum) {
            this.eventNum = eventNum;
        }
    }

    /**
     * 删除用户适配器
     */

    class DeleteUserListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return shiJianBeanList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return shiJianBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater layoutInflater = BaseActivity.this
                        .getLayoutInflater();
                convertView = layoutInflater.inflate(
                        R.layout.delete_user_item_layout, parent, false);
                convertView.setTag(convertView);
            } else {
                convertView = (View) convertView.getTag();
            }

            CheckBox checkBox = (CheckBox) convertView
                    .findViewById(R.id.userNameCheckBox);
            TextView userName = (TextView) convertView
                    .findViewById(R.id.userName);
            userName.setText(shiJianBeanList.get(position).name);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                             boolean isChecked) {
                    // TODO Auto-generated method stub
                    if (isChecked) {
                        usersList.add(shiJianBeanList.get(position).name);
                    }
                }
            });
            return convertView;
        }

    }

    /**
     * 管理员事件列表二级菜单
     *
     * @author
     */
    public class ShiJianItemOneBean {
        private String name;
        private String eventName;
        private String time;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getEventName() {
            return eventName;
        }

        public void setEventName(String eventName) {
            this.eventName = eventName;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }
    }

    /**
     * 管理员事件三级菜单
     *
     * @author mac
     */
    public class ShiJianItemThreeBean {
        private String name;// 相关人员姓名
        private String number;// 相关人员电话号码

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }

    }

    public void showDialog(String message) {
        if (progressDialog == null) {
            initDialog();
        }
        progressDialog.setMessage(message);
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    public void missDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void initDialog() {
        progressDialog = new ProgressDialog(this);
        // progressDialog.setIndeterminate(true);
        // progressDialog.setCancelable(true);
        progressDialog.setView(initProgressBarLayout());
    }

    /**
     * 初始化"正在刷新"...布局
     *
     * @return
     */
    public RelativeLayout initProgressBarLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        progressBarLayout = (RelativeLayout) inflater.inflate(
                R.layout.progressbar_popwindow_layout, null);
        return progressBarLayout;
    }

    public void startAnimation(View editText) {
        Animation shake = AnimationUtils.loadAnimation(this, R.drawable.shake);
        editText.startAnimation(shake);
    }

    /**
     * 接近目标报警是否已经开启
     *
     * @return 如果返回true 则表示开启了 报警功能，否则没有开启
     */
    public boolean isOpenBaoJing() {
        return preference.getBoolean("isOpenBaoJing", false);
    }

    public String getDistance(double distance) {
        DecimalFormat df = new DecimalFormat("0.00");
//		double d = 123.9078; 
        String lastDistance = df.format(distance);
        return lastDistance;
    }

    
    
    private void requestNewVersion() {
    	Controller HTTP = DefaultController.getHttpClient();
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", "1");
		HTTP.post(new DefaultRequest("newVersion", map), new AsyncHandler() {

			@Override
			public void onStart() {
				// TODO Auto-generated method
				Toast.makeText(BaseActivity.this, "正在检测新版本...", 5000).show();
				super.onStart();

			}

			@Override
			public void onSuccess(JSONResp response) {
				try {
					
//					{version:'最新版本号', changelog:'升级日志', downurl:'升级包下载地址'}
					
					
//					int result = response.getInt("result");
//					if (Integer.parseInt(response.getString("version")) > 1 ) {
//						//检测到新版本
//						newVersionUrl = response.getString("downurl");
//						showNewVersionDialog();
//					} else {
//						Toast.makeText(BaseActivity.this, "当前为最新版本", 5000).show();
//					}
					newVersionUrl = response.getString("downurl");
					showNewVersionDialog();

				} catch (Exception e) {
					e.printStackTrace();
				}
				super.onSuccess(response);
			}
			@Override
			public void onFailure(Throwable e, String response) {
				Toast.makeText(BaseActivity.this, "网络传输错误", 5000).show();
				super.onFailure(e, response);
			}
		});
	
    }
    
    
    private void showNewVersionDialog() {

		AlertDialog.Builder builder = new Builder(BaseActivity.this);
		builder.setMessage("检测到新版本");
	    builder.setTitle("提示");
		builder.setPositiveButton("升级", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				Intent intent = new Intent(BaseActivity.this,
						CheckUpgradeActivity.class);
				intent.putExtra("url", newVersionUrl);
				startActivity(intent);
			}
		});
        builder.setNegativeButton("不升级", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});

	    builder.create().show();
	
    }
    
    
    

}
